package com.project.api.ym.controller;

import com.alibaba.fastjson.JSONObject;
import com.project.api.common.ApiResponse;
import com.project.api.common.auth.LoginToken;
import com.project.api.ym.model.Admin;
import com.project.api.ym.service.AdminService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class AdminController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private final String pf="ym";
    private final String vpf="verify/ym";
    @Autowired
    private AdminService adminService;

    @RequestMapping(value=vpf+"/admin",method = RequestMethod.POST)
    @ResponseBody
    public String Admin(HttpServletRequest request, Model model,
                           @RequestBody JSONObject json){
        try {
            Object i=json.getOrDefault("id",0L);
            long id=Long.valueOf(String.valueOf(i));
            Boolean isCreate= (Boolean) json.getOrDefault("isCreate",false);
            HttpSession session=request.getSession();
            long aid = Long.valueOf((String) session.getAttribute(LoginToken.ADMIN));
            if (id>0L){
                adminService.UpdateAdmin(id,json);
            }else{
                adminService.CreateAdmin(json,aid,aid);
            }
            JSONObject obj=new JSONObject();
            obj.put("id",id);
            return ApiResponse.Ok("操作成功",obj);
        } catch (Exception e) {
            return ApiResponse.Fail(e.getMessage());
        }
    }

    @RequestMapping(value=vpf+"/admin_one",method = RequestMethod.GET)
    @ResponseBody
    public String AdminOne(@RequestParam(value="id",required = true)  String  id){
        try {
            long i = Long.valueOf(String.valueOf(id));
            Admin data = adminService.GetAdminInfo(i);
            return ApiResponse.Ok("success", data);
        }catch (Exception e){
            return ApiResponse.Fail(e.getMessage());
        }
    }
}
